package smashedapples.utils
{
	import flash.utils.ByteArray;
	
	import mx.utils.Base64Decoder;
	import mx.utils.Base64Encoder;
	
	public class ObjectSerializer
	{

		public static function decode(str:String):*
		{
			// '+' equals '-'  and '/' equals '_'
			
			if (str != null)
			{
				
				var myPattern : RegExp = new RegExp("-", "g"); 
				var myPattern2 : RegExp = new RegExp("_", "g"); 
				var myPattern3 : RegExp = new RegExp("~", "g"); 
				
				var urlModifiedString : String = str;
					urlModifiedString = urlModifiedString.replace(myPattern,"=");
					urlModifiedString = urlModifiedString.replace(myPattern2,"/");
					urlModifiedString = urlModifiedString.replace(myPattern3,"\n");
					
				
				var bytes:ByteArray = new ByteArray();
				var bDecoder : Base64Decoder = new Base64Decoder();
					bDecoder.decode(urlModifiedString);
				bytes = bDecoder.toByteArray() ;
				
				bytes.position = 0;
				
				return bytes.readObject();
			}
			return null;
			
		}
		
		public static function encode(obj:*):String
		{
			if(obj == null)
				return '';
			// '+' equals '-'  and '/' equals '_'
			
			var bytes:ByteArray = new ByteArray();
				bytes.writeObject( obj );
			
			var bEncoder : Base64Encoder = new Base64Encoder();
				bEncoder.encodeBytes(bytes);

			var myPattern : RegExp = new RegExp("=", "g"); 
			var myPattern2 : RegExp = new RegExp("/", "g");
			var myPattern3 : RegExp = new RegExp('\n', "g");
			
			var urlModifiedString : String = bEncoder.toString();
				urlModifiedString = urlModifiedString.replace(myPattern,"-");
				urlModifiedString = urlModifiedString.replace(myPattern2,"_");
				urlModifiedString = urlModifiedString.replace(myPattern3,"~");
			
			return urlModifiedString ;
		}

	}
}